package com.example.myapplication.activity;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

//权限申请
import com.example.myapplication.utils.GetPictureUtils;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.client.curl.CurlClient;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.myapplication.utils.CameraUtils;
import com.google.android.material.imageview.ShapeableImageView;

import com.example.myapplication.R;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import okhttp3.Call;

public class ProfileActivity extends AppCompatActivity {

    String username;

    ActivityResultLauncher<Intent> selectPhotoLauncher;     //相册打开

    //获取当前时间作为图片名称
    // 获取当前时间
    LocalDateTime now;

    // 定义时间格式化器
    DateTimeFormatter formatter;

    ActivityResultLauncher<Intent> takePhoto;    //拍照事件
    //权限请求
    final RxPermissions rxPermissions = new RxPermissions(this);
    private UploadManager manager;
    //是否拥有权限
    private boolean hasPermissions = false;
    private Button tv_back;
    private TextView tv_main_title;
    //底部弹窗
    private BottomSheetDialog bottomSheetDialog;
    //弹窗视图
    private View bottomView;
    //存储拍完照后的图片
    private File outputImagePath;
    //启动相机标识
    public static final int TAKE_PHOTO = 1;
    //启动相册标识
    public static final int SELECT_PHOTO = 2;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    //图片控件
    private ShapeableImageView ivHead;
    //Base64
    private String base64Pic;
    //拍照和相册获取图片的Bitmap
    private Bitmap orc_bitmap;

    private Button push;

    private byte[] photoData;  //图片数据
    private String photoName;  //图片名称

    private TextView tv_name;
    private TextView tv_sex;
    private TextView tv_phone;
    private TextView tv_regTime;

    //Glide请求图片选项配置
    private RequestOptions requestOptions = RequestOptions.circleCropTransform()
            .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
            .skipMemoryCache(true);//不做内存缓存


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        selectPhotoLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        // 对数据进行处理
                        if(data != null)
                        {
                            String imagePath = null;
//                            imagePath = CameraUtils.getImageOnKitKatPath(data, this);
//                            displayImage(imagePath);
                            Uri selectedPhotoUri = data.getData();
                            photoName = getPhotoNameFromUri(selectedPhotoUri);
                            photoData = getPhotoDataFromUri(selectedPhotoUri);
//                            Glide.with(ProfileActivity.this).load(imagePath).apply(requestOptions).into(ivHead);
                            pushToQiniu(photoData,photoName);
                        }
                    }
                });

        setContentView(R.layout.activity_profile);
        //去除默认标题栏
        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }

        //初始化图片上传配置
        String caPath = "src/cacert.pem";
        CurlClient client = new CurlClient(caPath);
        Configuration config = new Configuration.Builder()
                .requestClient(client) // 指定 HTTP/3 Client
                .build();
        manager = new UploadManager(config);

        init();

        ivHead = findViewById(R.id.iv_head);

        //检查版本
        checkVersion();

        //拍照回调
        takePhoto = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        // 对数据进行处理
                        if(data != null)
                        {
                            Bundle extras = data.getExtras();
                            if (extras != null && extras.containsKey("data")) {
                                Bitmap imageBitmap = (Bitmap) extras.get("data");
                                //转为byte[]
                                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                                imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                                byte[] imageData = stream.toByteArray();
                                // 格式化当前时间为字符串
                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && imageData != null) {
                                    now = LocalDateTime.now();
                                    String formattedDateTime = now.format(formatter);
                                    String name = formattedDateTime+"_"+username;
                                    GetPictureUtils.setImageBitmap(imageBitmap);
                                    pushToQiniu(imageData, name);
                                }else{
                                    Toast.makeText(ProfileActivity.this,"系统至少为Android 9",Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }
                });

        //取出缓存，将url加载出来
//        if(imageUrl != null){
//            Glide.with(this).load(imageUrl).apply(requestOptions).into(ivHead);
//        }
    }

    /**
     * 检查版本
     */
    private void checkVersion() {
        //Android6.0及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //权限请求
            rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(granted -> {
                if (granted) {//申请成功
                    hasPermissions = true;
                    showMsg("已获取权限");
                } else {//申请失败
                    showMsg("权限未开启");
                    hasPermissions = false;
                }
            });
        } else {
            //Android6.0以下
            showMsg("无需请求动态权限");
        }
    }

    public void init()
    {

        //展示初始化
        tv_name = (TextView) findViewById(R.id.et_user_name);
        tv_sex = (TextView) findViewById(R.id.tv_sex);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_regTime = (TextView) findViewById(R.id.tv_time);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        }

        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        username=sp.getString("loginUserName","default");

        //更新信息
        updateInformation();

        tv_back = (Button) findViewById(R.id.tv_back);
        tv_main_title = (TextView) findViewById(R.id.tv_main_title);

        tv_main_title.setText("个人中心");
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProfileActivity.this.finish();
            }
        });
    }

    public void changeAvatar(View view) {
        bottomSheetDialog = new BottomSheetDialog(this);
        bottomView = getLayoutInflater().inflate(R.layout.dialog_bottom, null);
        bottomSheetDialog.setContentView(bottomView);
        bottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet).setBackgroundColor(Color.TRANSPARENT);
        TextView tvTakePictures = bottomView.findViewById(R.id.tv_take_pictures);
        TextView tvOpenAlbum = bottomView.findViewById(R.id.tv_open_album);
        TextView tvCancel = bottomView.findViewById(R.id.tv_cancel);

        //拍照
        tvTakePictures.setOnClickListener(v -> {
            showMsg("拍照");
            takePhoto();
            bottomSheetDialog.cancel();
        });
        //打开相册
        tvOpenAlbum.setOnClickListener(v -> {
            showMsg("打开相册");
            openAlbum();
            bottomSheetDialog.cancel();
        });
        //取消
        tvCancel.setOnClickListener(v -> {
            bottomSheetDialog.cancel();
        });
        bottomSheetDialog.show();
    }

    //获取本地图片
    private void openAlbum() {
        if (!hasPermissions) {
            showMsg("未获取到权限");
            checkVersion();
            return;
        }
        selectPhotoLauncher.launch(CameraUtils.getSelectPhotoIntent());

    }
    //拍照
    private void takePhoto() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            takePhoto.launch(takePictureIntent);
        }
    }

    /**
     * 通过图片路径显示图片
     */
    private void displayImage(String imagePath) {
        if (!TextUtils.isEmpty(imagePath)) {
            //显示图片
            Glide.with(this).load(imagePath).apply(requestOptions).into(ivHead);

        } else {
            showMsg("图片获取失败");
        }
    }
    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    //获取图片名称
    private String getPhotoNameFromUri(Uri uri) {
        String photoName = null;
        if (uri != null) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                if (nameIndex != -1) {
                    photoName = cursor.getString(nameIndex);
                }
                cursor.close();
            }
        }
        return photoName;
    }

    //获取图片字符数据
    private byte[] getPhotoDataFromUri(Uri uri) {
        byte[] photoData = null;
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            if (inputStream != null) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                photoData = outputStream.toByteArray();
                inputStream.close();
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return photoData;
    }

    private void pushToQiniu(byte[] photoData,String photoName)
    {
        OkHttpUtils
                .get()
                .url("http://121.36.92.128:8086/getToken")
                .addParams("userid",username)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("okhttp",e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        manager.put(photoData, photoName, response,
                                new UpCompletionHandler() {
                                    @Override
                                    public void complete(String key, ResponseInfo info, JSONObject response_1) {
                                        if(info.isOK()){
                                            Log.i("qiniu", "Upload Success");
                                            Toast.makeText(ProfileActivity.this,"上传成功", Toast.LENGTH_SHORT).show();
                                            try {
                                                displayImage("http://rxl2k50ko.hb-bkt.clouddn.com/"+response_1.getString("key"));
                                                sendToDB("http://rxl2k50ko.hb-bkt.clouddn.com/"+response_1.getString("key"));
                                            } catch (JSONException e) {
                                                throw new RuntimeException(e);
                                            }
                                            System.out.println(response_1);
                                        }else{
                                            Log.i("qiniu", "Upload Fail");
                                            Toast.makeText(ProfileActivity.this,"上传失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                },null);
                    }
                });
    }

    //将url传回数据库
    private void sendToDB(String url)
    {
        OkHttpUtils
                .post()
                .addParams("userid",username)
                .addParams("picture",url)
                .url("http://121.36.92.128:8086/savePic")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if(response.equals("true"))
                            Log.i("saveToDB","successful");
                    }
                });
    }

    //更新信息
    private void updateInformation()
    {
        OkHttpUtils
                .get()
                .addParams("userid",username)
                .url("http://121.36.92.128:8086/profile")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if(response != null)
                        {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                tv_name.setText(jsonObject.getString("userName"));
                                tv_sex.setText(jsonObject.getString("sex"));
                                tv_phone.setText(jsonObject.getString("phone"));
                                tv_regTime.setText(jsonObject.getString("reg_time"));
                                String pic = jsonObject.getString("picture");
                                if(pic != null)
                                    displayImage(pic);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }

                        }else{
                            Toast.makeText(ProfileActivity.this,"用户不存在",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

}